package com.aabte.springcloudlearn.ribbonhystrixcustomerdemo.controller;

import com.aabte.springcloudlearn.common.beans.User;
import com.aabte.springcloudlearn.common.utils.CommonMethod;
import com.aabte.springcloudlearn.ribbonhystrixcustomerdemo.service.RibbonHystrixCustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.Future;

/**
 * @author Daniel
 */
@Slf4j
@RestController
public class RibbonHystrixCustomerController {

    @Autowired
    private RibbonHystrixCustomerService service;

    @GetMapping("/hystrix/hello")
    public String helloHystrix(){
        log.info("Start helloHystrix.");
        return service.hello();
    }

    @GetMapping("/sync/user/{id:\\d+}")
    public User sendSyncRequestGetUserById(
            @PathVariable(name = "id") Long userId){
        log.info("Start sendSyncRequestGetUserById. userId: {}", userId);
        User user = service.useSyncRequestGetUserById(userId);
        log.info("End sendSyncRequestGetUserById. user: {}", user);
        return user;
    }

    @GetMapping("/async/user/{id:\\d+}")
    public User sendAsyncRequestGetUserById(
            @PathVariable(name = "id") Long userId){
        log.info("Start sendAsyncRequestGetUserById. userId: {}", userId);
        User user = service.useSyncRequestGetUserById(userId);
        log.info("End sendAsyncRequestGetUserById. user: {}", user);
        return user;
    }

    @GetMapping("/annotation-async/user/{id:\\d+}")
    public User sendAnnotationAsyncRequestGetUserById(
            @PathVariable(name = "id") Long userId){
        log.info("Start sendAnnotationAsyncRequestGetUserById. userId: {}", userId);
        Future<User> userFuture = service.useAnnotationAsyncRequestGetUserById(userId);
        User user = null;
        try {
            user = userFuture.get();
        } catch (Exception e) {
            log.error(CommonMethod.getErrorStack(e));
        }
        log.info("End sendAnnotationAsyncRequestGetUserById. user: {}", user);
        return user;
    }



}
